from flask import current_app, redirect, flash, url_for, render_template
from flask_login import current_user, login_required

from apps.models.gift import Gift
from apps.models.wish import Wish
from apps.utils.mail import send_mail
from apps.view_models.gift_wish import GiftWishViewModel
from . import web
from apps.models.base import db


@web.route('/my/wish')
def my_wish():
    wishes = Wish.query.filter_by(uid=current_user.id, launched=False).all()
    isbn_list = [wish.isbn for wish in wishes]
    wish_gift_counts = Wish.get_user_wish(isbn_list)
    view_model = GiftWishViewModel(wishes, wish_gift_counts)
    return render_template('my_wish.html', wishes=view_model.books)


@web.route('/wish/book/<isbn>')
@login_required
def save_to_wish(isbn):
    if current_user.save_to_gift(isbn):
        with db.auto_commit():
            wish = Wish()
            wish.isbn = isbn
            wish.uid = current_user.id
            db.session.add(wish)
    else:
        flash('添加失败')
    return redirect(url_for('web.book_detail', isbn=isbn))


@web.route('/satisfy/wish/<int:wid>')
def satisfy_wish(wid):
    wish = Wish.query.get_or_404(wid)
    gift = Gift.query.filter_by(uid=current_user.id, isbn=wish.isbn).first()
    if not gift:
        flash('请先将此书添加至赠送清单！')
    else:
        send_mail(wish.user.email, subject='【鱼书】赠送提醒', template='email/satisify_wish.html', wish=wish, gift=gift)
        flash('已发送邮件提醒，届时会收到鱼漂。')
    return redirect(url_for('web.book_detail', isbn=wish.isbn))


@web.route('/wish/book/<isbn>/redraw')
@login_required
def redraw_from_wish(isbn):
    wish = Wish.query.filter_by(isbn=isbn, uid=current_user.id).first_or_404()
    with db.auto_commit():
        wish.delete()
    return redirect(url_for('web.my_wish'))
